package cn.com.callback
import cn.com.elite.Util
import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.com.elite.Util
/**
 * 工单查询API
 */

public class apiWoPD implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoPD.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            //解析Json
            JSONObject inJson = JSONObject.parseObject(callJson);

            //获取页面信息参数
            String in_operation_type = inJson.getJSONObject("data").getString("operation_type"); //工单操作类型，保存工单:CLOSE 下送工单：SENDNS 退单：BACK 失败结案：FAILED 工单结案：END 接管未关闭的工单：TAKE 催单：URGE 接管关闭的工单：TAKECL REOPEN：重新打开工单 ROBACK：撤回

            String in_wostepcomments = inJson.getJSONObject("data").getString("in_wostepcomments"); // 步骤处理意见
            String in_workorderflowdetail = inJson.getJSONObject("data").getString("in_workorderflowdetail"); // 步骤处理意见
            String in_modifieddate = inJson.getJSONObject("data").getString("in_modifieddate"); // 操作时间
            String in_elitetask_modifieddate = inJson.getJSONObject("data").getString("in_elitetask_modifieddate"); // 期望解决时间

            String in_s_objetive_guid = inJson.getJSONObject("data").getString("in_s_objetive_guid"); //当前objective_guid
            String in_s_customer_guid = inJson.getJSONObject("data").getString("in_s_customer_guid"); //当前customer_guid
            String in_objectivesubstatus= inJson.getJSONObject("data").getString("in_objectivesubstatus"); //当前工单操作状态
            String in_curstepstatus= inJson.getJSONObject("data").getString("in_curstepstatus"); //当前任务状态
            String in_stepexpired = inJson.getJSONObject("data").getString("in_stepexpired"); // 步骤过期时间
            String in_stepstart = inJson.getJSONObject("data").getString("in_stepstart"); // 步骤开始时间
            String in_cur_expiredlen = inJson.getJSONObject("data").getString("in_cur_expiredlen"); // 当前工单过期时长单位为s
            String in_cur_expiredflag = inJson.getJSONObject("data").getString("in_cur_expiredflag"); // 当前工单是否过期标志 1为已过期 0为未过期
            String in_workstarttime = inJson.getJSONObject("data").getString("in_workstarttime"); // 当前步骤操作开始时间
            String in_workendtime = inJson.getJSONObject("data").getString("in_workendtime"); // 当前步骤操作结束时间

            String in_oldhandlegroup_id = inJson.getJSONObject("data").getString("in_oldhandlegroup_id");// 原处理组
            String in_oldstaff_id = inJson.getJSONObject("data").getString("in_oldstaff_id");// 原处理人
            String in_r_map_id = inJson.getJSONObject("data").getString("in_r_map_id"); //当前mapid
            String in_r_node_id = inJson.getJSONObject("data").getString("in_r_node_id"); //当前nodeid
            String in_s_userid = inJson.getJSONObject("data").getString("in_s_userid"); //当前staffid
            String in_r_send_group = inJson.getJSONObject("data").getString("in_r_send_group"); //下送至组
            String in_r_send_staff = inJson.getJSONObject("data").getString("in_r_send_staff"); //下送至人

            String queryWorkOrderSQL = "SELECT uuid() as task_guid, n.nodemap_id as task_nod_id, '" + in_r_send_group + "' as task_group_id, '" + in_r_send_staff + "' as task_staff_id,n.workorderframe_id as objectivetype_id " +
            "FROM WO3_node_MAP n " +
            "LEFT JOIN wo3_nodemap_extend   e1 ON n.map_id = e1.map_id AND n.nodemap_id = e1.nodemap_id and e1.EXTENDID = 'MAINTASK' " +
            "left join wo3_nodemap_extend e2 ON e1.nodemap_id = e2.nodemap_id and n.map_id = e2.map_id and e2.EXTENDID = 'TASKGR' " +
            "left join wo3_nodemap_extend e3 ON e1.nodemap_id = e3.nodemap_id and n.map_id = e3.map_id and e3.EXTENDID = 'TASKSF' " +
            "WHERE 1=1 AND e1.extendvalue ='" + in_r_node_id + "'" +
            "and n.map_id ='" + in_r_map_id + "'";

            log.debug("执行任务数据查询SQL:" + queryWorkOrderSQL);
            List WorkOrderList = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");
            //获取总行数
            log.debug("执行工单查询数据SQL获取总条数:" + WorkOrderList.size());

            for (int i = 0; i < WorkOrderList.size(); i++) {

                String task_map_id = in_r_map_id;
                Map selectResultcm = WorkOrderList.get(i);
                String task_nod_id = selectResultcm.get("task_nod_id");
                String task_group_id = selectResultcm.get("task_group_id");
                String task_staff_id = selectResultcm.get("task_staff_id");
                String task_guid = selectResultcm.get("task_guid");
                String objectivetype_id = selectResultcm.get("objectivetype_id");

                log.debug("下送节点:" + task_nod_id);
                log.debug("下送组别:" + task_group_id);
                log.debug("下送人:" + task_staff_id);

                //查询当前处理人的角色
                String queryStaffRoleSQL = "select role_id from staffrole where staff_id = '" + task_staff_id + "' limit 1  ";
                log.debug("执行坐席角色数据查询SQL:" + queryStaffRoleSQL);
                List queryStaffRoleList = eliteBean.chaxun_sql(queryStaffRoleSQL, "dataSource");
                String staff_role_id = queryStaffRoleList.get(0).get("role_id");
                log.debug("staff_role_id:" + staff_role_id);

                String[] data = new String[3];
                //插入elitetask
                data[0] = "insert into elitetask (elitetask_guid,objective_guid,objectivetype_id,expectstarttime,expectendtime,priority,handleby_id,handlegroup_id,createdby,createddate,modifiedby,modifieddate,currentexpectstarttime,comments,customer_guid,curstepstatus,curstep_id,flowdetail,curstep_id_map,map_id,cur_roleid,objectivesubstatus,obflag,maintaskstep_id_map,back_node,back_group,back_staff) " +
                        "values( '" + task_guid + "','" + in_s_objetive_guid + "','" + objectivetype_id + "','" + in_modifieddate + "','" + in_elitetask_modifieddate + "','NORMAL','" + task_staff_id +  "','" + task_group_id + "','" + in_s_userid + "','" + in_modifieddate + "','" + in_s_userid + "','" + in_modifieddate + "','" + in_modifieddate + "','" + in_wostepcomments + "','" + in_s_customer_guid + "','" + in_curstepstatus + "','" + task_nod_id + "','" +  in_workorderflowdetail + "','" + task_nod_id + "','" + task_map_id + "','" + staff_role_id + "','" + in_objectivesubstatus + "','0',null,null,null,null)";
                //更新objective数据
                data[1] = "update objective set pd_deal_flag = 'YPD' " +
                          "where objective_guid = '" + in_s_objetive_guid + "'";
                //插入步骤信息表
                data[2] = "insert into workorderstep3(workorderstep_guid,workorder_guid,oldhandleby_id,oldhandlegroup_id,handleby_id,handlegroup_id,workorderstepstatus,comments," +
                        "modifieddate,from_stepidmap,to_stepidmap,stepexpired,stepstart,cur_expiredlen,cur_expiredflag,workstarttime,workendtime) " +
                        "values (uuid(), '" + in_s_objetive_guid + "','" + in_oldstaff_id + "','" + in_oldhandlegroup_id + "','" + in_r_send_staff + "','" + in_r_send_group + "','" + in_operation_type + "','" + in_wostepcomments + "','" +
                        in_modifieddate + "','" + in_r_node_id + "','" + task_nod_id + "','" + in_stepexpired + "','" + in_stepstart + "','" + in_cur_expiredlen + "','" + in_cur_expiredflag + "','" + in_workstarttime + "','" + in_workendtime + "')";

                log.debug("当前执行更新结果SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, 'dataSource');
                log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

                //调用短信发送接口发送短信
                String post_body = '''{"data":{"in_r_objectivesubstatus":"''' + in_objectivesubstatus + '''",''' +
                        '''"in_map_roleid":"''' + staff_role_id + '''",''' +
                        '''"in_r_remark":"",''' +
                        '''"in_s_objetive_guid":"''' + in_s_objetive_guid + '''",''' +
                        '''"in_s_elitetask_guid":"''' + task_guid + '''",''' +
                        '''"in_r_map_id":"''' + in_r_map_id + '''",''' +
                        '''"in_r_node_id":"''' + in_r_node_id + '''"}}'''

                String woMessageURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWoMessageEntrance";
                String woMessageResult = Util.doHttpPost(woMessageURL, post_body, "UTF-8", 5000, 0);
                JSONObject woMessageJson = JSONObject.parseObject(woMessageResult);
                String re_code = woMessageJson.getString("code");

            }

            long endTime = System.currentTimeMillis();
            result.put("code", 1);
            result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        }

        return result.toString();

    }
}